package com.sky.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Data
@AllArgsConstructor
@Slf4j
public class QiNiuOssUtil {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String url;

    /**
     * 七牛云实现文件上传
     * @param bytes 文件所对应的字节数组
     * @param fileName 文件名称
     * @return
     */
    public String upload(byte[] bytes, String fileName) {
        try {
            if (accessKey == null || accessKey.isEmpty() || secretKey == null || secretKey.isEmpty()) {
                throw new IllegalArgumentException("Access Key or Secret Key不能为空");
            }
        } catch (IllegalArgumentException e) {
            log.info("七牛云设置不能为空");
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadong());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        // 进行文件上传
        try {
            Response response = uploadManager.put(bytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        }catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder("http://");
        stringBuilder
                .append(url)
                .append("/")
                .append(fileName);
        log.info("文件上传到:{}", stringBuilder.toString());
        return stringBuilder.toString();
    }

}
